#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/10/10 15:10
# @Author : 吴敬超
# explain:
import netCDF4 as nc
import time as ti
import multiprocessing
from collections import OrderedDict
from collections import defaultdict

import json

#
# xlen = 1047
# ylen = 1497


print ti.strftime("%Y-%m-%d %H:%M:%S", ti.localtime())

file_path_wrf = '/data1/python/nc2json/wrf_2020070700_need.nc'
file_path_roms = '/data1/python/nc2json/roms_2020070700_need.nc'
ffpath = "/data1/python/jsonfile/"

#
# file_path_wrf = 'D:/nc2json/wrf_2020070700_need.nc'
# file_path_roms = 'D:/nc2json/roms_2020070700_need.nc'
# ffpath = "D:/nc2json/"

south_north = 409
west_east = 559

eta = 1047
xi = 1497
file_obj_roms = nc.Dataset(file_path_roms)
file_obj_wrf = nc.Dataset(file_path_wrf)

jsonsource = "TIME"
jsonlat = [-16.000000, 62.000000]
jsonnlat = 157
jsonlng = [39.000000, 178.000000]
jsonnlng = 279

ocean_time = file_obj_roms.variables['ocean_time']

ocean_times = nc.num2date(ocean_time[:], ocean_time.units)

romsu = file_obj_roms.variables['u'][:]
romsv = file_obj_roms.variables['v'][:]
romstemp = file_obj_roms.variables['temp'][:]
romszeta = file_obj_roms.variables['zeta'][:]
wrfRAINNC = file_obj_wrf.variables['RAINNC'][:]
wrft2 = file_obj_wrf.variables['T2'][:]
wrfolr = file_obj_wrf.variables['OLR'][:]
wrfwu = file_obj_wrf.variables['U10'][:]
wrfwv = file_obj_wrf.variables['V10'][:]


def dachange(da):
    if str(da) == '--':
        return 0.0
    else:
        return float(format(da, "0.1f"))


def filechanger(threadName, timenum):
    print "thread start Name is " + str(threadName)
    #
    listu = []
    listv = []
    listtemp = []
    listzeta = []
    listrain = []
    listt2 = []
    listolr = []
    listwu = []
    listwv = []
    video = OrderedDict()
    # video = defaultdict(list)

    video["source"] = jsonsource
    video["lat"] = jsonlat
    video["nlat"] = jsonnlat
    video["lng"] = jsonlng
    video["nlng"] = jsonnlng
    video["time"] = ocean_times[timenum].strftime("%Y-%m-%d_%H:%M:%S [UTC+8]")
    # ************************************************************************************
    #
    # video["u"] = romsu[timenum][0].flatten().tolist()
    # video["v"] = romsv[timenum][0].flatten().tolist()
    # video["temp"] = romstemp[timenum][0].flatten().tolist()
    # video["zeta"] = romszeta[timenum].flatten().tolist()

    for i in range(0, eta, 6):
        for j in range(0, xi, 6):
            listu.append(dachange(romsu[timenum][0][i][j]))
            listv.append(dachange(romsv[timenum][0][i][j]))
            listtemp.append(dachange(romstemp[timenum][0][i][j]))
            listzeta.append(dachange(romszeta[timenum][i][j]))
            # print "*ij***"
            # video["u"].append(dachange(romsu[timenum][0][i][j]))
            # video["v"].append(dachange(romsv[timenum][0][i][j]))
            # video["temp"].append(dachange(romstemp[timenum][0][i][j]))
            # video["zeta"].append(dachange(romszeta[timenum][i][j]))

    for sn in range(0, south_north, 6):
        for we in range(0, west_east, 6):
            listrain.append(dachange(wrfRAINNC[timenum][sn][we]))
            listt2.append(dachange(wrft2[timenum][sn][we]))
            listolr.append(dachange(wrfolr[timenum][sn][we]))
            listwu.append(dachange(wrfwu[timenum][sn][we]))
            listwv.append(dachange(wrfwv[timenum][sn][we]))
            # print "**snwe**"
            # video["rain"].append(dachange(wrfRAINNC[timenum][sn][we]))
            # video["t2"].append(dachange(wrft2[timenum][sn][we]))
            # video["olr"].append(dachange(wrfolr[timenum][sn][we]))
            # video["wu"].append(dachange(wrfwu[timenum][sn][we]))
            # video["wv"].append(dachange(wrfwv[timenum][sn][we]))

            # video["t2"] = wrft2[timenum].flatten().tolist()
            # video["olr"] = wrfolr[timenum].flatten().tolist()
            # video["wu"] = wrfwu[timenum].flatten().tolist()
            # video["wv"] = wrfwv[timenum].flatten().tolist()
            # rain = wrfRAINNC[timenum][sn][we]
            #
            # if str(rain) == '--':
            #     video["rain"].append(0.0)
            # else:
            #     video["rain"].append(format(rain, "0.1f"))

    # video["rain"] = wrfRAINNC[timenum].flatten().tolist()

    # json_str = json.dumps(video)
    # print json_str
    # json_str = json.dumps(video)
    # print json_str
    # crcm1.json
    video["u"] = listu
    video["v"] = listv
    video["temp"] = listtemp
    video["zeta"] = listzeta
    video["rain"] = listrain
    video["t2"] = listt2
    video["olr"] = listolr
    video["wu"] = listwu
    video["wv"] = listwv

    filename = ffpath + "crcm" + str(timenum) + ".json"

    with open(filename, "w") as f:
        json.dump(video, f)
    #
    # with open('videotest_datan.json', 'w') as json_file:
    #     json_file.write(json_str)

    # print ti.strftime("%Y-%m-%d %H:%M:%S", ti.localtime())
    print "thread end Name is" + str(threadName)

    print "%s: %s" % (threadName, ti.ctime(ti.time()))


if __name__ == "__main__":
    # print("main")

    print ti.strftime("%Y-%m-%d %H:%M:%S", ti.localtime())

    pool = multiprocessing.Pool(processes=8)

    for timenum in range(0, len(ocean_times), 6):
        Threadname = "process-" + str(timenum)

        pool.apply_async(filechanger, (Threadname, timenum,))

    pool.close()
    pool.join()

    print ti.strftime("%Y-%m-%d %H:%M:%S", ti.localtime())

    # filechanger("process1", 0)
